from lxml import etree
from util.selenium.webdriver.common.by import By


from spider_data.spiderBaseMethod import bm
from util.g import g


def parse_data(driver=None, text=''):
    try:
        tree = etree.HTML(text)
        # # 知识产权列表
        ip_record_list = tree.xpath('//tbody[@class="tableBody"]/tr')
        a = list()
        for r in ip_record_list:
            # # #  这里还需要将 co_id ， year 放入 value 字典中。
            ipr_item = {'ipr_id': '', 'ipr_type': '', 'ipr_getway': '', 'auth_num': '', 'auth_date': ''}
            # # #  这里需要编写一个函数用来把编号全部匹配出来。
            ipr_id_name = bm.get_first(r.xpath('./td[2]/text()'))
            ipr_item['ipr_id'] = bm.get_ids(ipr_id_name)

            # ipr_item['ipr_name'] = bm.get_first(r.xpath('./td[3]/text()'))
            # # #  这里需要查询数据库， 获取与之对应的 value
            ipr_type_name = bm.get_first(r.xpath('./td[4]/text()'))
            ipr_item['ipr_type'] = ipr_type_name
            ipr_getway_name = bm.get_first(r.xpath('./td[7]/text()'))
            ipr_item['ipr_getway'] = ipr_getway_name

            ipr_item['auth_num'] = bm.get_first(r.xpath('./td[6]/text()'))
            # # #  这里需要编写一个函数， 将字符串格式的日期 转换为 datetime.date 类型的日期。
            auth_date = bm.get_first(r.xpath('./td[5]/text()'))
            ipr_item['auth_date'] = bm.str_to_date(s=auth_date)
            a.append(ipr_item)
        # driver.switch_to.default_content()
        return a
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)

def parse_ip(driver=None):
    try:
        bm.detail_switch_iframe(driver=driver)
        ip_loc = (By.LINK_TEXT, '知识产权汇总表')

        bm.wait(driver=driver, ele_loc=ip_loc)

        driver.find_element(*ip_loc).click()
        bm.wait(driver=driver, ele_loc=g.title_loc)

        # page_num_objs = bm.get_page_num(driver=driver)
        # for i, pn in enumerate(page_num_objs, 1):
        WriteIPForm = list()
        i = 1
        while True:
            # pn_loc = (By.CSS_SELECTOR, g.page_css + f':nth-of-type({i})')
            if i == 1:
                bm.wait(driver=driver, ele_loc=g.table_loc)
            # if i != 1:
            #     bm.detail_switch_iframe(driver=driver)
            #     page_objs = bm.get_page_num(driver=driver)
            #     page_objs[i - 1].click()

            text = driver.page_source

            ipr_li = parse_data(driver=driver, text=text)
            WriteIPForm.extend(ipr_li)
            next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
            onclick = None
            try:
                onclick = next_btn.get_attribute("onclick")
            except Exception as err:
                g.logger.error("get next page button\' attribute error: {}".format(err))
            if onclick is None:
                # driver.switch_to.default_content()
                break
            else:
                bm.click(driver=driver, ele_loc=g.next_btn_loc)
                bm.wait(driver=driver, ele_loc=g.table_loc)
                i += 1
        return {"key": "WriteIPForm", "value": WriteIPForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)

























